import Mock from "mockjs";

const Random = Mock.Random;
const tokens = {
  admin: "admin-token",
  guest: "guest-token",
};

const users = {
  "admin-token": {
    id: 1,
    username: "管理员",
    avatar: "https://placeholder.co/100",
    role: "admin",
    permissions: ["user:manage", "content:manage"],
    isLogin: true,
  },
  "guest-token": {
    id: 2,
    username: "访客",
    avatar: "https://placeholder.co/100",
    role: "guest",
    permissions: [],
    isLogin: true,
  },
};

export default [
  {
    url: "/api/auth/login",
    method: "post",
    response: ({ body }) => {
      const { username } = typeof body === "string" ? JSON.parse(body) : body;
      console.log("Mock login received username:", username);

      const token = tokens[username];
      console.log("Generated token:", token);

      if (!token) {
        return {
          code: 401,
          message: "用户名或密码错误",
        };
      }

      return {
        code: 200,
        data: {
          token,
          expires: 24 * 60 * 60 * 1000,
        },
        message: "登录成功",
      };
    },
  },
  {
    url: "/api/user/:userId",
    method: "get",
    response: ({ params }) => {
      const { userId } = params;
      const userInfo = users[userId];
      console.log("Found userInfo:", userInfo);

      if (!userInfo) {
        return {
          code: 401,
          message: "获取用户信息失败",
        };
      }

      return {
        code: 200,
        data: userInfo,
        message: "获取用户信息成功",
      };
    },
  },
  {
    url: "/api/auth/logout",
    method: "post",
    response: () => {
      return {
        code: 200,
        message: "退出登录成功",
      };
    },
  },
  {
    url: '/api/user',
    method: 'post',
    response: ({ body, headers }) => {
      const data = typeof body === 'string' ? JSON.parse(body) : body;
      const { isRegister, username, password, email, userId, ...updateData } = data;
      
      if (isRegister) {
        // 注册操作
        const existingUser = Object.values(users).find(user => user.username === username);
        if (existingUser) {
          return {
            code: '400',
            message: '用户名已存在'
          };
        }

        // 创建新用户
        const userId = Random.id();
        const newUser = {
          id: userId,
          username,
          email: email || '',
          avatar: `https://placeholder.co/100`,
          role: 'user',
          permissions: ['basic:access'],
          isLogin: false, // 初始状态为未登录
          nickname: '',
          phone: '',
          address: '',
          description: ''
        };

        // 保存用户信息，但不生成token
        users[userId] = newUser;

        return {
          code: '200',
          data: {
            id: userId,
            username,
            email: email || ''
            // 不返回token
          },
          message: '注册成功，请登录'
        };
      } else {
        // 更新操作
        // 验证token
        const authToken = headers['authorization']?.split(' ')[1];
        if (!authToken || !users[authToken]) {
          return {
            code: '401',
            message: '未授权'
          };
        }

        // 验证用户ID
        if (!userId) {
          return {
            code: '400',
            message: '缺少用户ID'
          };
        }

        // 查找要更新的用户
        const userToUpdate = Object.values(users).find(user => user.id === userId);
        if (!userToUpdate) {
          return {
            code: '404',
            message: '用户不存在'
          };
        }

        // 更新用户信息
        Object.assign(userToUpdate, updateData);

        return {
          code: '200',
          data: userToUpdate,
          message: '更新成功'
        };
      }
    }
  }
];
